# -*- coding;utf-8 -*-
"""
File name : Doc2X.py.PY
Program IDE : PyCharm
Create file time: 2025/3/9 8:47
File Create By Author : 朱清闯
"""
import json
import requests
import time
base_url = "https://v2.doc2x.noedgeai.com"
secret = "sk-6rs61g3yjqpe35pjyvd5v67vevewdqxz"


def preupload():
    url = f"{base_url}/api/v2/parse/preupload"
    headers = {
        "Authorization": f"Bearer {secret}"
    }
    res = requests.post(url, headers=headers)
    if res.status_code == 200:
        data = res.json()
        if data["code"] == "success":
            return data["data"]
        else:
            raise Exception(f"get preupload url failed: {data}")
    else:
        raise Exception(f"get preupload url failed: {res.text}")


def put_file(path: str, url: str):
    with open(path, "rb") as f:
        res = requests.put(url, data=f)  # body为文件二进制流
        if res.status_code != 200:
            raise Exception(f"put file failed: {res.text}")


def get_status(uid: str):
    url = f"{base_url}/api/v2/parse/status?uid={uid}"
    headers = {
        "Authorization": f"Bearer {secret}"
    }
    res = requests.get(url, headers=headers)
    if res.status_code == 200:
        data = res.json()
        if data["code"] == "success":
            return data["data"]
        else:
            raise Exception(f"get status failed: {data}")
    else:
        raise Exception(f"get status failed: {res.text}")


def main(pdf_file: str, zip_file: str, to_file_type: str):
    url = f'{base_url}/api/v2/parse/pdf'
    headers = {
        "Authorization": f"Bearer {secret}",
    }
    with open(pdf_file, 'rb') as file:
        response = requests.post(url, headers=headers, data=file)  # 使用data
        print("response.text", response.text)
        data = json.loads(response.text)
        if data['code'] != 'success':
            return 'error', ''
    uid = data['data']['uid']
    while True:
        status_data = get_status(uid)
        print('status_data:', status_data)
        if status_data["status"] == "success":
            # 请求导出文件（异步）
            url = f"{base_url}/api/v2/convert/parse"
            headers2 = {
                "Authorization": f"Bearer {secret}",
                "Content-Type": "application/json",
            }
            data = {
                "uid": uid,
                "to": to_file_type,
                "formula_mode": "dollar",
                "filename": "my_markdown",
            }
            response = requests.post(url, headers=headers2, data=json.dumps(data))
            res = json.loads(response.text)
            if res['code'] != 'success':
                return 'fail'
            # 导出获取结果（需轮转）
            while True:
                url2 = f'{base_url}/api/v2/convert/parse/result?uid={uid}'
                response = requests.get(url2, headers=headers)
                print(response.text)
                res_data = json.loads(response.text)
                if res_data['code'] == 'success':
                    if res_data['data']['status'] == 'success':
                        url_final = res_data['data']['url']
                        # 用最终的url下载文件,并写入本地服务器
                        response_final = requests.get(url_final)
                        with open(zip_file, 'wb') as f:
                            f.write(response_final.content)
                            return 'success'
                    elif res_data['data']['status'] == 'processing':
                        time.sleep(2)
                else:
                    return 'failed'
        elif status_data["status"] == "failed":
            detail = status_data["detail"]
            print(f"parse failed: {detail}")
            return 'failed'
        elif status_data["status"] == "processing":
            progress = status_data["progress"]
            print(f"progress: {progress}")
            time.sleep(2)
